﻿package com.qinsoft.frame.utils;
 
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.qinsoft.frame.messages.WriteMessage;
/**
 * Description:数据库操作接口
 */
public class DbUtil {
	//数据访问工厂
	 private static SqlSessionFactory factory;
	 private DbUtil(){} 
	 
	 //加载mybatis配置文件,并成生数据库会话工厂
	 private static void CreateSessionFactory()
	 {
		 try { 
		    	System.out.println("开始加载数据库配置文件。。。。。。。。。。。");
		    	Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");  
		    	SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		    	factory = builder.build(reader); 
		    	reader.close();
		    	System.out.println("加载数据库配置文件完毕。。。。。。。。。。。");
		    	 
		    } catch (Exception e) { 
		    	WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.DbUtil.CreateSessionFactory()", e);
		    } 
	 }
	 /**
	  * 获取数据库适配器(自动提交事务) 
	  * @return 数据库操作对象
	  */
	 public static SqlSession getSqlMapClient()
	 {
		 if(factory==null)
		 {
			 CreateSessionFactory();
		 }
		 return factory.openSession(true);
	 } 
	 /**
	  * 获取数据库适配器(可设置是否自动提交事务) 
	  * @param flag:是否自动提交事务true:自动提交，false：手动提交
	  * @return 数据库操作对象
	  */
	 public static SqlSession getSqlMapClient(boolean flag)
	 {
		 if(factory==null)
		 {
			 CreateSessionFactory();
		 }
		 return factory.openSession(flag);
	 } 
		 
}
